//
//  SettingBankInfo.m
//  DaoZiJinFu
//
//  Created by woker on 16/6/27.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "SettingBankInfo.h"
#import "DZAddress.h"
@interface SettingBankInfo () <UIPickerViewDelegate,UIPickerViewDataSource,UIActionSheetDelegate,DZAddressDelegate> {
    NSArray *totalArray;
    NSMutableArray *provinceArray;
    NSMutableArray *cityArray;
    
    NSString *_cityId;
    NSString *_provinceId;
    UIView *_toolAllView;
    DZBankInfo *_bankInfo;
}
@property (copy, nonatomic) NSString *cityStr;
@property (copy, nonatomic) NSString *provinceStr;

@property (strong, nonatomic) UIView *toolPickerView;

@end

@implementation SettingBankInfo

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"填写开户行信息"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    
    _bankInfo = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
    NSString *str = [NSString stringWithString:_bankInfo.bank_card_number];
    _bankLab.text = [NSString stringWithFormat:@"%@(尾号%@)",_bankInfo.bank_name,[str substringFromIndex:str.length-4]];
    [_bankIcon sd_setImageWithURL:[NSURL URLWithString:_bankInfo.bank_logo_path] placeholderImage:[UIImage imageNamed:LOGO_PLACEHOLDER]];
    
    if (_bankInfo.bank_province != nil) {
        _cityId = _bankInfo.bank_city?:@"";
        _provinceId = _bankInfo.bank_province?:@"";
        [self getProvinceStr:_bankInfo.bank_province city:_bankInfo.bank_city];
    }
    if (_bankInfo.bank_branch != nil) {
        _branchText.text = _bankInfo.bank_branch;
    }
    _provinceStr = _bankInfo.bank_province?:@"";
    _cityStr = _bankInfo.bank_city?:@"";
    _cityLab.text = [NSString stringWithFormat:@"%@ %@",_provinceStr,_cityStr];
    
    _nextBtn.layer.masksToBounds = YES;
    _nextBtn.layer.cornerRadius = BTN_RADIUS;
    
    provinceArray = [NSMutableArray array];
    cityArray = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"City" ofType:@"plist"];
    NSDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    totalArray = data[@"data"];
    for (NSDictionary *dict in totalArray) {
        [provinceArray addObject:[[dict allKeys] lastObject]];
    }
    cityArray = totalArray[0][provinceArray[0]];
    
    _provinceStr = provinceArray[0];
    _cityStr = cityArray[0];
}

- (void)getProvinceStr:(NSString *)province city:(NSString *)cityId {
    DZgetBankProvinceRequest *request = [[DZgetBankProvinceRequest alloc] init];
    [DZNetAPI request:request success:^(id response) {
        if ([response[@"rt"] integerValue] == 1) {
            for (NSDictionary *data in response[@"data"]) {
                if ([data[@"code"] isEqualToString:province]) {
                    _provinceStr = data[@"name"];
                    [self getCityOfProvinceId:data[@"id"] city:cityId];
                    break;
                }
            }
        }
    } failure:^(NSError *error) {
    }];
}

- (void)getCityOfProvinceId:(NSString *)provinceId city:(NSString *)cityId {
    DZgetBankProvinceRequest *request = [[DZgetBankProvinceRequest alloc] init];
    request.p_id = provinceId;
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        if ([response[@"rt"] integerValue] == 1) {
            for (NSDictionary *data in response[@"data"]) {
                if ([data[@"code"] isEqualToString:cityId]) {
                    _cityStr = data[@"name"];
                    _cityLab.text = [_provinceStr stringByAppendingFormat:@" %@",_cityStr];
                    break;
                }
            }
        }
    } failure:^(NSError *error) {
    }];
    
}

- (void)setUpPickerView {
    _toolAllView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _toolAllView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    [[UIApplication sharedApplication].keyWindow addSubview:_toolAllView];
    UIView *toolView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-200, SCREEN_WIDTH, 200)];
    toolView.backgroundColor = [UIColor whiteColor];
    [_toolAllView addSubview:toolView];
    _toolPickerView = toolView;
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, 10, 60, 20)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:ORANGECOLOR forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(toolBarCanelClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:cancelBtn];
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-72, 10, 60, 20)];
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:ORANGECOLOR forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(toolBarDoneClick) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:confirmBtn];
    
    UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 160)];
    picker.delegate = self;
    picker.dataSource = self;
    picker.showsSelectionIndicator=YES;
    [toolView addSubview:picker];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (IBAction)nextClick:(id)sender {
    JSVIEWSHOW;
    NSDictionary *params = @{@"id":_bankInfo.id?:@"",
                             @"province":_provinceStr,
                             @"city":_cityStr,
                             @"branch":_branchText.text};
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"User/editBankCardBranch";
    request.params = params;
    [DZNetAPI request:request success:^(id response) {
        JSVIEWHIDE;
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            JSSHOW(model.msg);
            [theUser setObject:[NSNumber numberWithBool:YES] forKey:ISSETBANK];
            [theUser synchronize];
            [CommTools setUserInfo:response];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            JSSHOW(model.msg);
        }
    } failure:^(NSError *error) {
        JSVIEWHIDE;
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (IBAction)chooseCityClick:(id)sender {
    [_branchText resignFirstResponder];
    [self setUpPickerView];
    return;
   DZAddress *DZaddress = [[DZAddress alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    DZaddress.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:DZaddress];
}

- (void)DZAddressView:(DZAddress *)DZAddress selectProvince:(NSString *)province ProvinceId:(NSString *)provinceId city:(NSString *)city cityId:(NSString *)cityId {
    _provinceStr = province;
    _cityStr = city;
    _provinceId = provinceId;
    _cityId = cityId;
    _cityLab.text = [NSString stringWithFormat:@"%@ %@",province,city];
    [DZAddress removeFromSuperview];
    DZAddress = nil;
}

- (void)nextBtnUsabled {
    if (_branchText.text.length && _cityLab.text.length) {
        _nextBtn.backgroundColor = BLUE_COLOR;
        _nextBtn.userInteractionEnabled = YES;
    } else {
        _nextBtn.backgroundColor = UNUSEABLECOLOR;
        _nextBtn.userInteractionEnabled = NO;
    }
}
- (IBAction)branchChanged:(id)sender {
    [self nextBtnUsabled];
}
- (void)toolBarCanelClick {
    [_toolAllView removeFromSuperview];
}
- (void)toolBarDoneClick {
    [_toolAllView removeFromSuperview];
    _cityLab.text = [NSString stringWithFormat:@"%@ %@",_provinceStr,_cityStr];
    [self nextBtnUsabled];
}




#pragma mark -- pickerView Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (!component) {
        return provinceArray.count;
    } else {
        return [cityArray count];
    }
}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (!component) {
        return provinceArray[row];
    } else {
        return cityArray[row];
    }
    
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (!component) {
        NSString *provinceStr = [[totalArray[row] allKeys] lastObject];
        _provinceStr = provinceStr;
        cityArray = totalArray[row][provinceArray[row]];
        
        NSInteger subRow = [pickerView selectedRowInComponent:1] > cityArray.count-1 ? cityArray.count-1 : [pickerView selectedRowInComponent:1];
        _cityStr = [NSString stringWithString:cityArray[subRow]];
        [pickerView reloadComponent:1];
        
    } else {
        _cityStr = [NSString stringWithString:cityArray[row]];
    }
}

@end
